<%@ page import="java.util.List" %>
<%@ page import="com.luna.service.PhaseService" %>
<%@ page import="com.luna.serviceImpl.PhaseServiceImpl" %>
<%@ page import="com.luna.service.NoteService" %>
<%@ page import="com.luna.serviceImpl.NoteServiceImpl" %>
<%@ page import="com.luna.beans.*" %>
<%@ page import="com.luna.serviceImpl.MessageServiceImpl" %>
<%@ page import="com.luna.service.MessageService" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<%
  int book_id = ((Book) request.getAttribute("book")).getId();

  /*
   * 获取图书章节列表
   * */
  PhaseService phaseService = new PhaseServiceImpl();
  List<Phase> phaseList = phaseService.phaseListInBook(book_id);
  request.setAttribute("phaseList", phaseList);

  /*
  * 获取图书笔记列表
  * */
  NoteService noteService = new NoteServiceImpl();
  List<Note> noteList = noteService.noteList(book_id);
  request.setAttribute("noteList", noteList);

  if (request.getSession().getAttribute("user") != null) {
    MessageService messageService = new MessageServiceImpl();
    List<ShowMessage> messageList = messageService.msgList(((User) request.getSession().getAttribute("user")).getId());
    request.setAttribute("messageList", messageList);
  }
%>

<html>
<head>
  <title>${requestScope.book.getName()}</title>
  <link type="text/css" rel="stylesheet" href="static/dist/css/bootstrap.min.css"/>
  <script type="text/javascript" src="static/js/jquery-3.7.0.min.js"></script>
  <script type="text/javascript" src="static/dist/js/bootstrap.min.js"></script>
  <style>
    @keyframes loop {
      0% {
        transform: translateX(500px);
        -webkit-transform: translateX(500px);
      }
      100% {
        transform: translateX(-100%);
        -webkit-transform: translateX(-100%);
      }
    }
    @-webkit-keyframes loop {
      0% {
        transform: translateX(500px);
        -webkit-transform: translateX(500px);
      }
      100% {
        transform: translateX(-100%);
        -webkit-transform: translateX(-100%);
      }
    }
    .scroll-bar {
      width: 500px;
      margin: 10px auto;
      overflow: hidden;
      background-color: #ffffff;
      border-radius: 5px;
      padding: 5px;
    }
    .roll {
      white-space: nowrap;
      animation: 10s loop linear infinite normal;
      display: inherit;
    }
    .my-dropdown {
      position: relative;
      display: inline-block;
    }
    .my-dropdown-content {
      display: none;
      position: absolute;
      background-color: #f9f9f9;
      min-width: 300px;
      box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
      padding: 12px 16px;
      transform: translateY(16px);
      z-index: 1;
      color: black;
    }
    .my-dropdown:hover .my-dropdown-content {
      display: block;
    }
    .side-bar-background {
      height: 100vh;
      width: 20vw;
      position: fixed;
      top: 0;
      background-color: lightgray;
      z-index: -1;
    }
    .side-bar {
      width: 20vw;
      margin-top: 80px;
      height: 87vh;
      overflow-y: scroll;
      overflow-x: hidden;
      position: fixed;
    }
    .side-bar::-webkit-scrollbar {
      display: none;
    }
    .base-info {
      position: absolute;
      left: 25vw;
      top: 80px;
      width: 60vw;
      height: auto;
    }
    .phase-detail {
      cursor: pointer;
    }
  </style>
  <script type="text/javascript">
    const base_href = window.location.href.slice(0, window.location.href.lastIndexOf('/'))
    function removePhase() {
      $('.btn-delete-phase').click(function () {
        console.log($(this).attr("uid"))
        $.ajax({
          url: base_href + '/RemovePhase?phase_id=' + $(this).attr("uid"),
          type: "GET",
          success: function (data) {
            location.reload()
          }
        })
      })
    }
    function removeNote() {
      $('.btn-delete-note').click(function () {
        $.ajax({
          url: base_href + '/RemoveNote?note_id=' + $(this).attr("uid"),
          type: "GET",
          success: function (data) {
            location.reload()
          }
        })
      })
    }
    function showPhaseDetail() {
      $('.phase-detail').click(function () {
        console.log($(this).text())
        $('#phase-detail-modal-title').text($(this).text())
        $('#phase-detail-modal-content').text($(this).parent().children("p").eq(0).text())
        $('#phase-detail-modal').modal('show')
      })
    }
    function showNoteDetail() {
      $('.note-detail').click(function () {
        console.log($(this).text())
        $('#note-detail-modal-title').text($(this).text())
        $('#note-detail-modal-content').text($(this).parent().children("p").eq(0).text())
        $('#note-detail-modal').modal('show')
      })
    }
  </script>
  <script type="text/javascript">
    window.onload = () => {
      removePhase()
      removeNote()
      showPhaseDetail()
      showNoteDetail()
    }
    const toHome = () => {
      window.location.href = base_href + '/'
    }
    const toLogin = () => {
      window.location.href = base_href + '/login.jsp'
    }
    const toRegister = () => {
      window.location.href = base_href + '/register.jsp'
    }
    const logout = () => {
      window.location.href = base_href + '/LogoutServlet'
    }
    const uploadPhase = () => {
      $.ajax({
        url: base_href + '/PhaseAddition?book_id=' + ${requestScope.book.getId()},
        type: "POST",
        data: $("#phase-addition-form").serialize(),
        dataType: "text",
        success: function (data) {
          if (data === "true") {
            location.reload()
          } else {
            alert("后台数据提交失败！")
          }
        }
      })
    }
    const uploadNote = () => {
      $.ajax({
        url: base_href + '/NoteAddition?book_id=' + '${requestScope.book.getId()}',
        type: "POST",
        data: $("#note-addition-form").serialize(),
        dataType: "text",
        success: function (data) {
          if (data === "true") {
            location.reload()
          } else {
            alert("后台数据提交失败！")
          }
        }
      })
    }
    const backToLastPage = () => {
      <c:choose>
        <c:when test="${sessionScope.user.getState() == 1}">
          window.location.href = base_href + '/admin-index.jsp'
        </c:when>
        <c:otherwise>
          window.location.href = base_href + '/index.jsp'
        </c:otherwise>
      </c:choose>
    }
    const removeMessage = () => {
      $.ajax({
        url: base_href + '/ReadMessages?user_id=' + '${requestScope.user.getId()}',
        type: 'GET',
        success: function (data) {
          location.reload()
        }
      })
    }
    const removeBook = () => {
      $().modal('show')
    }
    const confirmRemoveBook = () => {
      $.ajax({
        url: base_href + '/RemoveBook?book_id=' + ${requestScope.book.getId()},
        type: 'GET',
        success: function(_data) {
          window.location.href = base_href + '/'
        }
      })
    }
  </script>
</head>
<body>
  <nav class="navbar navbar-inverse" style="position: fixed; width: 100%; z-index: 1;">
    <div class="container-fluid">
      <!-- Brand and toggle get grouped for better mobile display -->
      <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-9" aria-expanded="false">
          <span class="sr-only">Toggle navigation</span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" onclick="toHome()" style="cursor: pointer;">图书笔记管理系统</a>
      </div>

      <!-- Collect the nav links, forms, and other content for toggling -->
      <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-9">
        <ul class="nav navbar-nav">
          <li class="active"><a onclick="toHome()" style="cursor: pointer;">首页</a></li>
        </ul>
        <p class="nav navbar-nav scroll-bar">
          <span class="roll">欢迎来到图书笔记管理系统</span>
        </p>
        <ul class="nav navbar-nav navbar-right">
          <c:if test="${sessionScope.user != null}">
            <li class="my-dropdown"><a>
              <div>
                <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
                <c:choose>
                  <c:when test="${messageList.size() != 0}">
                    您有新消息
                  </c:when>
                  <c:otherwise>
                    您没有新消息
                  </c:otherwise>
                </c:choose>
              </div>
              <div class="my-dropdown-content">
                <ul class="list-group">
                  <c:forEach items="${messageList}" var="item">
                    <li class="list-group-item" style="font-size: 5px;">您分享发布的书籍《${item.book}》下有新笔记！</li>
                  </c:forEach>
                </ul>
                <div style="text-align: center">
                  <button class="btn btn-default btn-xs" onclick="removeMessage()">已读全部</button>
                </div>
              </div>
            </a></li>
          </c:if>

          <c:choose>
            <c:when test="${sessionScope.user != null}">
              <li><a>欢迎，${sessionScope.user.getNickname()}！</a></li>
              <li><a style="cursor: pointer" onclick="logout()">退出登录</a></li>
            </c:when>
            <c:otherwise>
              <li><a href="login.jsp">登录</a></li>
              <li><a href="register.jsp">注册</a></li>
            </c:otherwise>
          </c:choose>
        </ul>
      </div><!-- /.navbar-collapse -->
    </div><!-- /.container-fluid -->
  </nav>

  <div class="side-bar-background">
  </div>
  <div class="side-bar">
    <ul class="nav nav-pills nav-stacked nav-pills-stacked-example">
      <li role="presentation"><a href="#title">抬头</a></li>
<%--      <li role="presentation"><a href="#">第一章</a></li>--%>
      <c:forEach items="${phaseList}" var="item" varStatus="status">
        <li role="presentation"><a href="#phase-${status.index + 1}">第${status.index + 1}章</a></li>
      </c:forEach>
    </ul>
  </div>

  <div class="base-info" id="title">
    <button class="btn btn-default" onclick="backToLastPage()" style="margin-bottom: 5px;">返回</button>
    <div class="jumbotron" style="padding-left: 50px;" >
      <h1>${requestScope.book.getName()}</h1>
      <p>${requestScope.book.getAuthor()}</p>
      <c:if test="${sessionScope.user.getId() == requestScope.book.getUploaderId()}">
        <p style="float: right; margin-right: 50px;">
          <button class="btn btn-danger" style="margin-right: 5px;" onclick="removeBook()">删除本书</button>
          <button class="btn btn-primary" data-toggle="modal" data-target="#myModal">添加章节</button>
        </p>
      </c:if>
    </div>
    <c:forEach items="${phaseList}" var="item" varStatus="status">
      <div class="panel panel-default" id="phase-${status.index + 1}">
        <div class="panel-body">
          <h3 class="phase-detail">${item.name}</h3>
          <hr>
          <p>${item.content}</p>
          <c:if test="${requestScope.book.getUploaderId() == sessionScope.user.getId()}">
            <p style="float: right; margin-right: 10px;">
              <button class="btn btn-danger btn-delete-phase" uid="${item.id}">删除章节</button>
            </p>
          </c:if>
        </div>
      </div>
    </c:forEach>
    <c:if test="${phaseList.size() == 0}">
      <div>
        <h3 style="font-weight: bolder;">目前本书暂无章节，请联系上传者添加！</h3>
      </div>
    </c:if>
    <hr />
    <h2>笔记</h2>
    <c:if test="${sessionScope.user != null}">
      <button class="btn btn-primary" data-toggle="modal" data-target="#noteModal" style="margin-bottom: 5px;">写下我的读书笔记</button>
    </c:if>
    <c:forEach items="${noteList}" var="item">
      <div class="jumbotron" style="padding-left: 10px;">
        <h4 style="font-weight: bold; cursor: pointer;" class="note-detail">${item.title}</h4>
        <hr />
        <p>${item.content}</p>
        <c:if test="${item.uploader_id == sessionScope.user.getId()}">
          <p style="float: right; margin-right: 10px;">
            <button class="btn btn-danger btn-delete-note" uid="${item.id}">删除笔记</button>
          </p>
        </c:if>
      </div>
    </c:forEach>
    <c:if test="${noteList.size() == 0}">
      <div>
        <h4 style="font-weight: bold">目前本书暂无笔记，写下第一个笔记吧</h4>
      </div>
    </c:if>
  </div>

  <!-- Phase Modal -->
  <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title">新增章节</h4>
        </div>
        <div class="modal-body">
          <form id="phase-addition-form">
            <div class="row">
              <div class="col-sm-2" style="line-height: 100%; text-align: center;">
                <label>标题：</label>
              </div>
              <div class="col-lg-10">
                <input class="form-control" type="text" name="phase-name" placeholder="请输入章节标题"/>
              </div>
            </div>
            <div class="row" style="margin-top: 10px;">
              <div class="col-sm-2" style="line-height: 100%; text-align: center;">
                <label>内容：</label>
              </div>
              <div class="col-lg-10">
                <textarea class="form-control" name="phase-content" style="height: 200px;" placeholder="请输入章节内容"></textarea>
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
          <button type="button" class="btn btn-primary" onclick="uploadPhase()">添加</button>
        </div>
      </div>
    </div>
  </div>

  <%-- Note Modal --%>
  <div class="modal fade" id="noteModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title">新增笔记</h4>
        </div>
        <div class="modal-body">
          <form id="note-addition-form">
            <div class="row">
              <div class="col-sm-2" style="line-height: 100%; text-align: center;">
                <label>标题：</label>
              </div>
              <div class="col-lg-10">
                <input class="form-control" type="text" name="note-title" placeholder="请输入笔记标题"/>
              </div>
            </div>
            <div class="row" style="margin-top: 10px;">
              <div class="col-sm-2" style="line-height: 100%; text-align: center;">
                <label>内容：</label>
              </div>
              <div class="col-lg-10">
                <textarea class="form-control" name="note-content" style="height: 200px;" placeholder="请输入笔记内容"></textarea>
              </div>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
          <button type="button" class="btn btn-primary" onclick="uploadNote()">添加</button>
        </div>
      </div>
    </div>
  </div>

<%--  Phase Detail Modal --%>
  <div class="modal fade" id="phase-detail-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title"></h4>
        </div>
        <div class="modal-body">
          <h3 id="phase-detail-modal-title" style="font-weight: bold;"></h3>
          <hr />
          <p id="phase-detail-modal-content" style="margin-top: 15px;"></p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        </div>
      </div>
    </div>
  </div>

  <%--  Note Detail Modal --%>
  <div class="modal fade" id="note-detail-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title"></h4>
        </div>
        <div class="modal-body">
          <h3 id="note-detail-modal-title" style="font-weight: bold;"></h3>
          <hr />
          <p id="note-detail-modal-content" style="margin-top: 15px;"></p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        </div>
      </div>
    </div>
  </div>

  <%--  Remove Book Modal --%>
  <div class="modal fade" id="remove-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title"></h4>
        </div>
        <div class="modal-body" style="background-color: lightcoral;">
          删除后不可恢复！
        </div>
        <div class="modal-footer">
          <button class="btn btn-danger" onclick="confirmRemoveBook()">确认删除</button>
          <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
        </div>
      </div>
    </div>
  </div>
</body>
</html>
